package com.itealabs.postjson.ext;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itealabs.postjson.PostJsonService;

/**
 * 
 * @version $Id: SpringServletAdapter.java 34 2010-09-11 13:46:47Z iteahere $
 * @author itea
 * @date 2010-4-16
 */
public class SpringServletAdapter extends HttpServlet {

	private static final long serialVersionUID = 1674370457683779858L;

	private WebApplicationContext appCtx;
	
	private PostJsonService service;
	
	private String contentType;
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Map<String, Object> ctx = new Hashtable<String, Object>();
		ctx.put("javax.servlet.http.HttpServletRequest", req);
		ctx.put("javax.servlet.http.HttpServletResponse", resp);
		ctx.put("javax.servlet.http.HttpServlet", this);
		
		resp.setContentType(contentType == null
				? "application/json; charset=utf-8"
				: contentType);
		service.service(req.getReader(), resp.getWriter(), ctx);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.contentType = config.getInitParameter("contentType");
		
		appCtx = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
		if(appCtx == null)
			throw new ServletException("WebApplicationContext NOT FOUND.");
		String serviceName = config.getInitParameter("postJsonService");
		this.service = (PostJsonService)appCtx.getBean(serviceName == null
				? "postJsonService" : serviceName, PostJsonService.class);
	}

}
